package com.mentalhealthplatform.studentV3.service;

import com.mentalhealthplatform.appModels.Detail;
import com.mentalhealthplatform.global.redisGuard.CacheService;
import com.mentalhealthplatform.studentV3.repository.DetailRepositoryV3;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Pear
 */
@Service
public class DetailServiceV3 {

    private static final Logger logger = LoggerFactory.getLogger(DetailServiceV3.class);

    @Autowired
    private DetailRepositoryV3 detailRepositoryV3;

    @Autowired
    private CacheService cacheService;

    // 缓存的 key 前缀
    private static final String DETAIL_CACHE_KEY_PREFIX = "detail:";
    private static final String ALL_DETAILS_CACHE_KEY = "all:details";

    /**
     * 获取所有详细信息，优先从 Redis 缓存中获取。
     */
    public List<Detail> getAllDetails() {
        List<Detail> details = cacheService.getCacheData(ALL_DETAILS_CACHE_KEY, List.class);

        if (details == null || details.isEmpty()) {
            // 缓存中不存在，查询数据库
            details = detailRepositoryV3.findAll();

            if (details != null && !details.isEmpty()) {
                // 缓存数据库查询结果，设置随机过期时间防止雪崩
                cacheService.setCacheData(ALL_DETAILS_CACHE_KEY, details, 300 + new java.util.Random().nextInt(100), TimeUnit.SECONDS);
            } else {
                logger.warn("No details found in the database.");
            }
        }

        return details;
    }

    /**
     * 根据类型获取详细信息，优先从 Redis 缓存中获取。
     */
    public Detail getDetailByType(String type) {
        String cacheKey = DETAIL_CACHE_KEY_PREFIX + type;
        Detail detail = cacheService.getCacheData(cacheKey, Detail.class);

        if (detail == null) {
            // 缓存中不存在，查询数据库
            detail = detailRepositoryV3.findByType(type);

            if (detail != null) {
                // 缓存数据库查询结果，设置随机过期时间防止雪崩
                cacheService.setCacheData(cacheKey, detail, 300 + new java.util.Random().nextInt(100), TimeUnit.SECONDS);
            } else {
                logger.warn("No detail found for type: {}", type);
            }
        }

        return detail;
    }

    /**
     * 保存新的详细信息，同时更新缓存。
     */
    public Detail saveDetail(Detail detail) {
        Detail savedDetail = detailRepositoryV3.save(detail);

        // 更新缓存
        String cacheKey = DETAIL_CACHE_KEY_PREFIX + detail.getType();
        cacheService.setCacheData(cacheKey, savedDetail, 300 + new java.util.Random().nextInt(100), TimeUnit.SECONDS);

        // 清理所有详情的缓存
        cacheService.setCacheData(ALL_DETAILS_CACHE_KEY, null, 0, TimeUnit.SECONDS);

        return savedDetail;
    }

    /**
     * 更新现有的详细信息，同时更新缓存。
     */
    public Detail updateDetail(String type, Detail detail) {
        Detail existingDetail = detailRepositoryV3.findByType(type);

        if (existingDetail != null) {
            existingDetail.setTitle(detail.getTitle());
            existingDetail.setDescription(detail.getDescription());
            Detail updatedDetail = detailRepositoryV3.save(existingDetail);

            // 更新缓存
            String cacheKey = DETAIL_CACHE_KEY_PREFIX + type;
            cacheService.setCacheData(cacheKey, updatedDetail, 300 + new java.util.Random().nextInt(100), TimeUnit.SECONDS);

            // 清理所有详情的缓存
            cacheService.setCacheData(ALL_DETAILS_CACHE_KEY, null, 0, TimeUnit.SECONDS);

            return updatedDetail;
        } else {
            logger.warn("No existing detail found for type: {}", type);
        }

        return null; // 如果未找到相应的详细信息，返回 null
    }

    /**
     * 删除详细信息，同时清理缓存。
     */
    public boolean deleteDetail(String type) {
        Detail existingDetail = detailRepositoryV3.findByType(type);

        if (existingDetail != null) {
            detailRepositoryV3.delete(existingDetail);

            // 清理缓存
            String cacheKey = DETAIL_CACHE_KEY_PREFIX + type;
            cacheService.setCacheData(cacheKey, null, 0, TimeUnit.SECONDS);

            // 清理所有详情的缓存
            cacheService.setCacheData(ALL_DETAILS_CACHE_KEY, null, 0, TimeUnit.SECONDS);

            return true;
        } else {
            logger.warn("No detail found to delete for type: {}", type);
        }

        return false;
    }

    /**
     * 获取介绍文本
     */
    public String getIntroductionText() {
        Detail introductionDetail = detailRepositoryV3.findByType("introduction");
        if (introductionDetail!= null) {
            return introductionDetail.getDescription();
        }
        return "";
    }
}
